<template>
  <div class="count">
    <span
      class="count-decrease"
      @click="decrease"
      v-analytics.click="{
        action: 'Cut Goods',
        category: 'Detail Page',
        label: goodsId + ' ' + goodsTitle,
      }"
    >
      -
    </span>
    <input class="count-input" v-model="currentValue" type="text" name="count" pattern="\d*">
    <span
      class="count-add"
      @click="add"
      v-analytics.click="{
        action: 'Add Goods',
        category: 'Detail Page',
        label: goodsId + ' ' + goodsTitle,
      }"
    >
      +
    </span>
  </div>
</template>

<script>
export default {
  name: 'number',
  props: {
    goodsId: String,
    goodsTitle: String,
    value: Number,
    max: Number,
    min: Number,
    step: {
      type: Number,
      default: 1,
    },
  },
  data() {
    return {
      currentValue: this.value,
    }
  },
  methods: {
    decrease() {
      this.currentValue -= this.step
    },
    add() {
      this.currentValue += this.step
    },
  },
  watch: {
    currentValue() {
      if (typeof this.min !== 'undefined' && this.currentValue < this.min) {
        this.currentValue = this.min
      }

      if (this.max && this.currentValue > this.max) {
        this.currentValue = this.max
      }

      this.$emit('on-change', this.currentValue)
      this.$emit('input', this.currentValue)
    },
    value(val) {
      this.currentValue = val
    },
  },
}
</script>

<style lang="scss">
.count {
  display: table;
  font-size: 16px;
  width: 180px;
  height: 40px;
  border: 1px solid #D5D5D5;
  table-layout: fixed;
}

.count-decrease,
.count-input,
.count-add {
  display: table-cell;
  vertical-align: middle;
  height: 40px;
  text-align: center;
}

.count-decrease {
  width: 40px;
  border-right: 1px solid #D5D5D5;
  color: #4A4A4A;
}

.count-add {
  width: 40px;
  text-align: center;
  border-left: 1px solid #D5D5D5;
  color: #4A4A4A;
}

.count-input {
  -webkit-appearance: none;
  width: 100px;
  border: 0;
  text-align: center;
  font-size: 14px;
  &:focus {
    outline: 0;
  }
}
</style>
